package com.lagou.service;

import com.alibaba.fastjson.JSON;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.collect.Lists;
import com.lagou.constants.RedisKeyConstants;
import com.lagou.model.Response;
import com.lagou.model.vo.RecommendVO;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommand.Setter;
import com.netflix.hystrix.HystrixCommandGroupKey.Factory;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
import javax.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import redis.clients.jedis.JedisCluster;


@Service
public class HomeServiceImpl implements HomeService {

  private static Logger logger = LoggerFactory.getLogger(HomeServiceImpl.class);

  /**
   * 推荐列表key
   */
  private static final String RECOMMEND_LIST_CACHE_NAME = "recommendList";

  /**
   * 本地缓存
   */
  private Cache<String, List<RecommendVO>> localCache = CacheBuilder.newBuilder()
          .refreshAfterWrite(3, TimeUnit.SECONDS).build(new CacheLoader<String, List<RecommendVO>>() {
            @Override
            public List<RecommendVO> load(String key) throws Exception {
              return getRecommendListFromRedis();
            }
          });

  /**
   * 默认推荐列表
   */
  private List<RecommendVO> defaultRecommendList;

  @Autowired
  private JedisCluster jedisCluster;

  @PostConstruct
  public void init() {
    // 启动时加载推荐列表到内存
//    List<RecommendVO> recommendVOList = getRecommendListFromRedis();
//    if (!CollectionUtils.isEmpty(recommendVOList)) {
//      localCache.put(RECOMMEND_LIST_CACHE_NAME, recommendVOList);
//    }

    // TODO 从配置加载默认的推荐列表，暂时使用hard code
    defaultRecommendList = Lists.newArrayList(
        new RecommendVO("默认职位", "2020-08-12", "FTE", "10K-20K", "lagou", "招聘"));
  }

  @Override
  public Response<List<RecommendVO>> getRecommendList() {
    try {
      List<RecommendVO> recommendVOList = localCache
          .get(RECOMMEND_LIST_CACHE_NAME, new Callable<List<RecommendVO>>() {
            @Override
            public List<RecommendVO> call() throws Exception {
              HystrixCommand<List<RecommendVO>> defaultGroup = new HystrixCommand<List<RecommendVO>>(
                  Setter.withGroupKey(
                      Factory.asKey("DefaultGroup"))) {
                @Override
                protected List<RecommendVO> run() throws Exception {
                  Thread.sleep(3000L);
                  return getRecommendListFromRedis();
                }

                @Override
                protected List<RecommendVO> getFallback() {
                  logger.info("从redis中加载缓存列表超时，返回默认列表");
                  return defaultRecommendList;
                }
              };
              return defaultGroup.execute();
            }
          });
      return new Response<>(recommendVOList);
    } catch (Exception e) {
      logger.error("加载缓存失败", e);
    }

    return new Response<>(defaultRecommendList);
  }

  /**
   * 从Redis获取推荐列表
   *
   * @return
   */
  private List<RecommendVO> getRecommendListFromRedis() {
    logger.info("从redis中加载缓存列表");
    String recommendListStr = jedisCluster.get(RedisKeyConstants.getRecommendListKey());
    if (!StringUtils.isEmpty(recommendListStr)) {
      List<RecommendVO> recommendVOList = JSON
          .parseArray(recommendListStr, RecommendVO.class);
      return recommendVOList;
    }

    return null;
  }
}
